$(function(){ Tasklog.init() });

var Tasklog=Tasklog||{}

Tasklog.init=function(){
	this.DB.init();
	this.Toolbar.init();
	this.drawTasks();
}

Tasklog.drawTasks=function(completed){
	$('.taskgrp').remove(); // remove all tasks and events
	
	/*** populate tasks ***/	
	var self=this, tasks, tLen=0, rows=new Array(), grp=''
	tasks=this.DB.getTasks(completed);
	if (tasks) tLen=tasks.length
	for (var i=0; i<tLen; i++){
		var tsk=tasks[i];
		var rowStr='<tr class="task'+(tsk.status?' task-done':'')+'" id="'+tsk.id+'"><td class="task-dd"></td><td class="task-check"><div></div></td><td class="task-description">'+this.Tags.taskTags(tsk.tags)+'<div contenteditable="true">'+tsk.description+'</div></td></tr>';		
		rows.push(rowStr);
	}
	grp+='<fieldset class="taskgrp"><table class="task-table"><tbody>';
	if (rows.length>0) grp+=rows.join(' ');
	// ad empty row if no tasks
	else if (!completed) grp+='<tr class="task"><td class="task-dd"></td><td class="task-check"><div></div></td><td class="task-description"><div contenteditable="true"></div></td></tr>';
	grp+='</tbody></table></fieldset>';
	$('body').append(grp);
	
	/*** init events ***/	
	$('.task-table tbody').sortable({  // init drag&drop
		connectWith: '.task-table tbody', //dd between groups
		handle: '.task-dd',
		containment: 'body', // constrain dd to 
		axis: 'y', // dd vertically only
		distance: 10, // mouse down distance to trigger dd
		helper: function(e, ui) { ui.children().each(function(){ $(this).width($(this).width()) }); return ui; },
		forcePlaceholderSize: true,
		placeholder: 'ui-state-highlight',
		revert: true,
		tolerance: 'pointer',
		update: function(ev, ui){ self.Task.ddEnd(ui.item[0],ui.item.context.nextElementSibling) }
	});
	$('.taskgrp .task').each(function(idx,item){ self.Task.init(idx,item) }); //init each task events
	$(document).click(function(){self.reset.call(self)}); //init hiding menus etc. on body click
	$(document).keydown(function(e){ // init global keystrokes
		if (e.which==27) self.reset.call(self,true);
		if (e.which==191){ e.stopPropagation(); e.preventDefault(); self.Toolbar.actionHelp(); }
	});	
	$('.tag').each(function(idx,item){ self.Tags.init(item) }); // tag events
}

Tasklog.reset=function(force){
	if (typeof force!='boolean') force=false;
	this.Window.hide(force);
	this.Toolbar.menuHide(); 
	this.Tags.collapseAll(); 
}
